module GYLite
{
	/**资源对象，包含资源以及资源的引用计数，引用计数为0时，资源会被回收*/
	export class ResObject
	{
		public static id:number=0;
		public type:number;
		/**引用计数，当引用计数为0时，资源会被释放,如非必要，勿修改此值*/
		private _count:number;
		/**资源，如BitmapData，直接调取并不增加应用计数count，不需调用relRes释放，如需增加计数，请调用getRes，释放请调用relRes*/
		public res;
		/**资源加载的路径*/
		public pathKey:string;
		/**附属资源*/
		public param:any;
		public inPool:boolean;
		private _bornTime:number;
		private _id:number;
		public constructor()
		{
			let s = this;
			s._count = 0;
			s.param = {};
			s._id = ++ResObject.id;
		}
		/**id*/
		public get id():number
		{
			return this._id;
		}
		/**获取资源时，请尽量使用getRes，以便引用计数*/
		public getRes():any
		{
			var s = this;
			++s._count;
			return s.res;
		}
		/**资源释放时，请把引用设置为null，避免重复释放*/
		public relRes():void
		{
			var s = this;
			--s._count;
			if(s._count < 0)
				throw(new Error("资源重复释放"));
		}
		public clear(gc:boolean=true):void
		{
			var s = this;
			if(s.inPool)return;
			if(CommonUtil.GYIs(s.res,egret.Texture))
			{
				if (s.res.bitmapData && s.res.bitmapData.source && s.res.bitmapData.source.src) {
					var url = s.res.bitmapData.source.src;
					if (url.indexOf("blob:") == 0) {
						var winURL = window["URL"] || window["webkitURL"];
						try {
							winURL.revokeObjectURL(url);
						}
						catch (e) {
							egret.$warn(1037);
						}
					}
				}
				//存在atlasName，则是合批图集，移除图集
				if(s.param.atlasName)
					AtlasRender.getInstance().removeAtlas(s.param.atlasName);
				//存在合批管理器，移除合批
				if(s.res.$batchManager)
					(<egret.Texture>s.res).$batchManager.dispose();
				if(s.res)
					s.res.dispose();
			}
			if(s.type == GYLoader.TYPE_SOUND)
			{
				(<egret.Sound>s.res).close();
			}
			if(s.type == GYLoader.TYPE_ATLAS)
			{
				if(s.param)
				{
					let len:number;
					//子图
					len = s.param.subRes.length;
					for(var key in s.param.subRes)
					{
						s.param.subRes[key].clear();
					}
					s.param.subRes = null;
					//同名图集
					if(s.param.atlases)
					{
						len = s.param.atlases.length;
						while(--len>-1)						
							(<ResObject>s.param.atlases[len]).clear();
						s.param.atlases.length = 0;
					}
				}				
			}			
			s.type = 0;
			s.res = null;
			s._count = 0;
			s.param = {};
			ResObject._pool.push(this);
			s.inPool = true;
		}
		/**引用数量*/
		public get count():number
		{
			return this._count;
		}
		
		private static _pool;
		// private static _s:Single;
		public static getInstance():ResObject
		{		
			let res:ResObject;	
			if(!ResObject._pool)
			{
				//_s=new Single;
				ResObject._pool=[];
			}
			if(ResObject._pool.length==0)
				res =  new ResObject();
			else
				res = ResObject._pool.pop();
			res.inPool = false;
			res.param = {};
			res._bornTime = Date.now();
			return res;
		}
		/**生产时间*/
		public get bornTime():number
		{
			return this._bornTime;
		}
	}
}